const { Tray, Menu, dialog } = require('electron')
const path = require('path')

function createTray(app, win) {
    // 添加窗口关闭确认功能
    win.on('close', (event) => {
        // 阻止默认关闭行为
        event.preventDefault()
        
        // 显示确认对话框
        dialog.showMessageBox({
            type: 'question',
            title: '确认关闭',
            message: '确定要关闭应用程序吗？',
            buttons: ['取消', '确定'],
            defaultId: 0,
            cancelId: 0
        }).then((response) => {
            // 如果用户点击确定按钮（索引为1）
            if (response.response === 1) {
                // 允许窗口关闭并退出应用
                app.quit()
            }
        })
    })
    
    const tray = new Tray(path.resolve(__dirname, './icon.ico'))
    tray.setToolTip('Bookmark')
    tray.on('click', (e) => {
        if (e.shiftKey) {
            app.quit()
        } else {
            win.isVisible() ? win.hide() : win.show()
        }
    })
    tray.setContextMenu(Menu.buildFromTemplate([

        {
            label: '打开窗口', click: () => {
                win.show()
            },
            accelerator: 'CTRL+SHIFT+Z'
        },
        {
            label: '隐藏窗口', click: () => {
                win.hide()
            },
            accelerator: 'CTRL+SHIFT+X'
        },
        {
            label: '退出', click: () => {
                app.quit()
            },
            accelerator: 'Alt+F4'
        },
    ]))
}

module.exports = createTray